package cn.com.homeyoda.aimate.aihealth.ui.login;

import static cn.com.homeyoda.aimate.aihealth.utils.AppConstants.LOGIN_SUCCESS;

import android.app.Application;
import android.graphics.Bitmap;
import android.os.Build;
import android.util.Log;

import androidx.annotation.NonNull;


import com.jeremyliao.liveeventbus.LiveEventBus;
import com.wzq.mvvmsmart.event.StateLiveData;
import com.wzq.mvvmsmart.utils.EncodeUtils;
import com.wzq.mvvmsmart.utils.ImageUtils;
import com.wzq.mvvmsmart.utils.KLog;
import com.wzq.mvvmsmart.utils.RegexUtils;
import com.wzq.mvvmsmart.utils.RxUtils;
import com.wzq.mvvmsmart.utils.ToastUtils;

import java.util.concurrent.TimeUnit;

import cn.com.homeyoda.aimate.aihealth.base.BaseViewModel;
import cn.com.homeyoda.aimate.aihealth.bean.BaseResponse2;
import cn.com.homeyoda.aimate.aihealth.bean.LoginBean;
import cn.com.homeyoda.aimate.aihealth.bean.LoginQrCodeBean;
import cn.com.homeyoda.aimate.aihealth.data.Repository;
import cn.com.homeyoda.aimate.aihealth.utils.ImageUtil;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * Created By 刘纯贵
 * Created Time 2020/4/30
 */
public class LoginViewModel extends BaseViewModel<Repository> {
    public final StateLiveData<Bitmap> qrCodeData;

    public LoginViewModel(@NonNull Application application, Repository model) {
        super(application, model);
        qrCodeData = new StateLiveData<>();
    }

    /**
     * 获取登录二维码
     */
    public void getLoginQrCode() {
        model.getLoginQrCode()
                .compose(RxUtils.observableToMain())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(LoginViewModel.this)
                .subscribe(new Observer<BaseResponse2<LoginQrCodeBean>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        qrCodeData.postLoading();
                    }

                    @Override
                    public void onNext(BaseResponse2<LoginQrCodeBean> response) {
                        if (response.getCode() == 200) {
                            KLog.d(TAG, "onNext response = " + response);
                            LoginQrCodeBean loginQrCodeBean = response.getData();
                            byte[] bytes = EncodeUtils.base64Decode(loginQrCodeBean.getImage());
                            Bitmap bitmap = ImageUtils.bytes2Bitmap(bytes);
//                            Bitmap bitmap = ImageUtil.base64ToBitmap(loginQrCodeBean.getImage());
                            qrCodeData.postValueAndSuccess(bitmap);
                            if (bitmap != null) {
                                selectFamilyLoginByCodeWithPolling(loginQrCodeBean.getLoginSignCode());
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        KLog.e("进入onError" + e.getMessage());
                        qrCodeData.postError();
                    }

                    @Override
                    public void onComplete() {
                        KLog.e("进入onComplete");
                    }
                });
    }

    /**
     * 通过轮询的方式实现扫码登录，10s轮询一次。
     *
     * @param loginSignCode 扫码登录的code
     */
    public void selectFamilyLoginByCodeWithPolling(String loginSignCode) {
        Observable.interval(10, TimeUnit.SECONDS)
                .takeWhile(index -> true)
                .flatMap(index -> model.selectFamilyLoginByCode(loginSignCode))
                .compose(RxUtils.observableToMain())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(LoginViewModel.this)
                .subscribe(new Observer<BaseResponse2>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        qrCodeData.postLoading();
                        // 保存Disposable以便可以取消订阅
                        pollingDisposable = d;
                    }

                    @Override
                    public void onNext(BaseResponse2 response) {
                        KLog.d(TAG, "onNext response = " + response);
                        if (response.getCode() == 200) {
                            String phone = response.getMsg();
                            if (RegexUtils.isMobileSimple(phone)) {
                                login(phone);
                                // 登录成功后停止轮询
                                stopPolling();
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        KLog.e("进入onError: " + e.getMessage());
                        qrCodeData.postError();
                        // 发生错误时也可以考虑停止轮询
                        stopPolling();
                    }

                    @Override
                    public void onComplete() {
                        KLog.e("进入onComplete");
                    }
                });
    }

    private Disposable pollingDisposable;

    // 停止轮询的方法
    public void stopPolling() {
        if (pollingDisposable != null && !pollingDisposable.isDisposed()) {
            pollingDisposable.dispose();
        }
    }

    /**
     * 登录
     *
     * @param phone 手机号
     */
    public void login(String phone) {
        // TODO: 2025/4/18 改成正常获取sn的方法 
        model.login(Build.SERIAL, phone)
        // model.login(Build.SERIAL, phone)
                .compose(RxUtils.observableToMain())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(LoginViewModel.this)
                .subscribe(new Observer<BaseResponse2<LoginBean>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(BaseResponse2<LoginBean> response) {
                        if (response.getCode() == 200) {
                            KLog.d(TAG, "onNext response = " + response);
                            LoginBean loginBean = response.getData();
                            //保存用户信息
                            model.saveFamilyId(loginBean.getFamilyId());
                            model.saveFaceId(loginBean.getFaceId());
                            model.savePhone(loginBean.getPhone());
                            model.saveUserId(loginBean.getUserId());
                            model.saveDeviceId(loginBean.getDeviceId());
                            ToastUtils.showLong("登录成功！");
                            Log.i("huadi","登录成功===faceid===="+model.getFaceId());
                            LiveEventBus.get(LOGIN_SUCCESS).post(loginBean.getUserId());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        KLog.e("进入onError" + e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        KLog.e("进入onComplete");
                    }
                });
    }
}
